<template>
  <div :id="id" class="app-vap"></div>
</template>

<script>
import Vap from "video-animation-player";
let id = Math.round(Math.random() * (19999 - 1) + 1); // id序号
export default {
  props: {
    src: {
      type: String,
      required: true
    },
    jsonSrc: {
      type: String,
      default: ""
    },
    json: {
      type: Object,
      default: () => {}
    },
    loop: {
      type: Boolean,
      default: false
    },
    onFinished: {
      type: Function,
      default: () => {}
    }
  },

  data() {
    return {
      id: `vap-id-${id++}` // 动态生成id
    };
  },

  async mounted() {
    let json = {};
    if (this.jsonSrc) {
      try {
        const res = await fetch(this.jsonSrc).then(res => res.json());
        json = res;
      } catch (error) {
        console.log(error);
      }
    } else {
      json = this.json;
    }

    console.log(json, this.src, this.id);
    // 创建player
    const container = document.getElementById(this.id);
    const vapWidth = json.info.w;
    const vapHeight = json.info.h;
    const cHeight = container.clientHeight;
    const cWidth = container.clientWidth;
    let h = 0;
    let w = 0;
    if (vapWidth / cHeight < cWidth / cHeight) {
      //以高为准
      h = Math.min(vapHeight, cHeight);
      if (vapHeight > cHeight) {
        w = (cHeight / vapHeight) * vapWidth;
      } else {
        w = (vapHeight / cHeight) * vapWidth;
      }
    } else {
      //以宽为准
      w = Math.min(vapWidth, cWidth);
      if (vapWidth > cWidth) {
        h = (cWidth / vapWidth) * vapHeight;
      } else {
        h = (vapWidth / cWidth) * vapHeight;
      }
    }

    if (vapHeight > cHeight) {
      w = (cHeight / vapHeight) * vapWidth;
    } else {
      w = (vapHeight / cHeight) * vapWidth;
    }
    // console.log(container, vapWidth, vapHeight, this.src, this.json);
    const vapPlayer = new Vap({
      container: container,
      src: this.src,
      config: json,
      width: w,
      height: h,
      loop: this.loop,
      fps: json.info.fps,
      mute: false,
      type: 2,
      beginPoint: 0,
      accurate: true
    });
    vapPlayer.play();
    vapPlayer.on("ended", () => {
      vapPlayer.destroy();
      document.getElementById(this.id).parentElement.remove();
      this.onFinished?.();
    });
  }
};
</script>

<style lang="scss">
.app-vap {
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100vw;
  height: 100vh;
  pointer-events: none;
  canvas {
    // margin-left: 50%;
    // transform: translateX(-50%);
  }
}
</style>
